package com.zhang.IO.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * NIO客户端
 */
public class NioClient {

    /**
     * 启动
     * 1.连接服务器
     * 2.向服务端发送数据
     * 3.接受服务器响应
     */
    public void start(String name) throws IOException {
//        1.连接服务器
        SocketChannel socketChannel=SocketChannel.open(
                new InetSocketAddress("127.0.0.1",8000));
        System.out.println("连接成功");
//        3.接受服务器响应
//        从新创建Selector
        Selector selector=Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        new Thread (new NioClientHandler(selector)).start();
//        2.向服务端发送数据
        Scanner scanner=new Scanner(System.in);
        while (scanner.hasNextLine())
        {
            String request=scanner.nextLine();
            if (request!=null && request.length()>0)
            {
                socketChannel.write(Charset.forName("UTF-8").encode(name+":  "+request));
            }
        }



    }
    public  static void main(String[] agr0) throws IOException {
        new NioClient().start("张三");
        new NioClient().start("李四");
    }
}
